package com.zeny.coding.dto;


import com.zeny.coding.util.DtoUtil;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import org.springframework.util.DigestUtils;

import javax.xml.bind.ValidationException;
import java.util.HashSet;
import java.util.List;

@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class UserDto {
    private String id;

    private String loginName;

    private String name;

    private String password;

    private String token;

    /**
     * <h2>验证码</h2>
     **/
    private String imageCode;

    /**
     * <h2>图片验证码token</h2>
     **/
    private String imageCodeToken;

    /**
     * <h2>所有资源，用于前端页面控制</h2>
     **/
    private List<ResourceDto> resources;

    /**
     * <h2>所有资源，用于前端页面控制</h2>
     **/
    private HashSet<String> requests;


    public void isValidForSave() throws ValidationException {
        DtoUtil.valid(this.loginName, true, 1, 50);
        DtoUtil.valid(this.name, true, 1, 50);
        DtoUtil.valid(this.password, true, 1, 32);
        this.id = null;
        //密码二次加密
        md5();
    }

    public void isValidForUpdate() throws ValidationException {
        DtoUtil.valid(this.id, true, 1, 19);
        DtoUtil.valid(this.name, true, 1, 50);
        this.password = null;
        this.loginName = null;
    }

    public void validForResetPassword() throws ValidationException {
        DtoUtil.valid(this.id, true, 1, 19);
        DtoUtil.valid(this.password, true, 1, 32);
        //密码二次加密
        md5();
        this.loginName = null;
        this.name = null;
    }

    public void validForLogin() throws ValidationException {
        DtoUtil.valid(this.loginName, true, 1, 50);
        DtoUtil.valid(this.password, true, 1, 32);
        DtoUtil.valid(this.imageCode, true, 1, 10);
        DtoUtil.valid(this.imageCodeToken, true, 1, 20);
        md5();
        this.id = null;
        this.name = null;
    }

    private void md5() {
        this.password = DigestUtils.md5DigestAsHex(this.password.getBytes());
    }

}